package com.credit.mola.app.ui.user.activity

import android.annotation.SuppressLint
import android.app.PendingIntent
import android.graphics.Paint
import android.text.Editable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextWatcher
import android.text.method.LinkMovementMethod
import android.text.style.ForegroundColorSpan
import android.text.style.UnderlineSpan
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.activity.result.IntentSenderRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.credit.mola.app.R
import com.credit.mola.app.adapter.AmountAdapter
import com.credit.mola.app.analysis.TestAnalysisInit
import com.credit.mola.app.databinding.ActivityUserLoginBinding
import com.credit.mola.app.pro.ProActivity
import com.credit.mola.app.ui.credit.activity.CreditActivity
import com.credit.mola.app.utils.BarUtils
import com.credit.mola.app.utils.DensityUtils
import com.credit.mola.app.utils.analysis.util.GoogleInstallUtil
import com.credit.mola.app.utils.config.Configs
import com.credit.mola.app.utils.event.EventType
import com.credit.mola.app.utils.event.track.TrackEventManager
import com.credit.mola.app.utils.helper.ActivityStackHelper
import com.credit.mola.app.utils.helper.CustomConfigHelper
import com.credit.mola.app.utils.http.AppUrls
import com.credit.mola.app.utils.http.AppUrls.addCommonParams
import com.credit.mola.app.utils.http.IHttpCallback
import com.credit.mola.app.utils.log.HHLog
import com.credit.mola.app.utils.rv.LinearDecoration
import com.google.android.gms.auth.api.identity.GetPhoneNumberHintIntentRequest
import com.google.android.gms.auth.api.identity.Identity
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject


/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/5/21 19:28
 * @Annotation：用户登录
 */
class UserLoginActivity: ProActivity() {
    lateinit var binding: ActivityUserLoginBinding
    var mAmountAdapter: AmountAdapter? = null

    override fun getRootView(): View {
        binding = ActivityUserLoginBinding.inflate(layoutInflater)
        return binding.root
    }

    @SuppressLint("SetTextI18n")
    override fun initView() {
        //关闭当前页面以外的所有页面
        ActivityStackHelper.finishAllActivity(UserLoginActivity::class.java)

        binding.parentLayout.setPadding(0, BarUtils.getStatusBarHeight(),0,0)

        initRvAmount()
        checkNextState()

        val stringAccept = String.format(getString(R.string.login_accept),getString(R.string.app_show_name))
        val stringPrivacy = getString(R.string.login_privacy_policy)
        val stringShow = "$stringAccept $stringPrivacy"
        val spString = SpannableString(stringShow)
        val start = stringShow.indexOf(stringPrivacy)
        val end = start + stringPrivacy.length
        spString.setSpan(ForegroundColorSpan(getColor(R.color.FFFF8378)), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //下划线
        spString.setSpan(UnderlineSpan(), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textPrivacy.text = spString
        // 确保TextView可以接收点击事件
        binding.textPrivacy.movementMethod = LinkMovementMethod.getInstance();

        //时区区号
        binding.textCode.text = "+${Configs.getSPString(Configs.SPKEY.SIKADWA_TIMEZONE_CODE)}"
        binding.textCode.paint.flags = Paint.UNDERLINE_TEXT_FLAG//下划线
        binding.textCode.paint.isAntiAlias = true//抗锯齿
    }

    override fun initListener() {
        //客服
        binding.imgKefu.setOnClickListener {
            showKefuDialog("Login Page")
            addEvent(EventType.CLICK.CLICK_CUSTOMER,"Login Page")
        }
        binding.textMaskMobile.setOnClickListener {
            addEvent(EventType.CLICK.CLICK_USER_LOGIN_SELF_MOBILE,"")
            loadCreditMolaSelfMobile()
        }
        //电话号码入框监听
        binding.editText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                binding.textMaskMobile.text = getEditMobile()
                checkNextState()
            }
        })
        binding.editText.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                binding.editText.clearFocus()
                true
            }
            false
        }
        //电话号码输入框焦点监听
        binding.editText.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus) {
                addEvent(EventType.FORM.FORM_LOGIN_MOBILE, getEditMobile())
            }
        }

        //隐私政策切换
        binding.checkBox.setOnCheckedChangeListener { _, isChecked ->
            checkNextState()
            when (isChecked) {
                true -> {
                    addEvent(EventType.CLICK.CLICK_LOGIN_PRIVACY_AGREE, "")
                }

                false -> {
                    addEvent(EventType.CLICK.CLICK_LOGIN_PRIVACY_DENY, "")
                }
            }
        }

        //Next
        binding.btnNext.setOnClickListener {
            //记录埋点并立即上报
            TrackEventManager.trackEventNow(EventType.CLICK.CLICK_LOGIN_NEXT, "")
            binding.editText.clearFocus()
            //发送验证码
            showLoading()
            loginAction("0000","YES")
        }

        // Privacy policy
        binding.textPrivacy.setOnClickListener {
            onIntent(com.credit.mola.app.ui.PrivacyPolicyActivity::class.java)
        }
    }

    override fun initData() {
        val amountList = arrayListOf<String>()
        val amountString = getAmount()
        for (i in amountString.indices){
            amountList.add(amountString[i].toString())
        }
        mAmountAdapter?.data = amountList

        binding.editText.visibility = View.VISIBLE
        binding.textMaskMobile.visibility = View.VISIBLE
    }

    private fun initRvAmount(){
        binding.rvAmount.setHasFixedSize(true)
        binding.rvAmount.isNestedScrollingEnabled = false
        binding.rvAmount.isFocusableInTouchMode = false //不需要焦点
        val decoration = DensityUtils.dp2px(14f)
        binding.rvAmount.addItemDecoration(LinearDecoration(0, decoration, 0, 0))
        val layoutManager = LinearLayoutManager(getContext())
        layoutManager.orientation = RecyclerView.HORIZONTAL
        binding.rvAmount.layoutManager = layoutManager
        mAmountAdapter = AmountAdapter(binding.rvAmount)
        mAmountAdapter?.setOnItemChildClickListener { parent, childView, position ->
            val item = this.mAmountAdapter?.getItem(position)
        }
        binding.rvAmount.adapter = mAmountAdapter
    }

    /**
     * 设置按钮状态
     */
    private fun checkNextState() {
        if (binding.checkBox.isChecked && getEditMobile().isNotEmpty()) {
            binding.btnNext.alpha = 1f
            binding.btnNext.isEnabled = true
        } else {
            binding.btnNext.alpha = 0.2f
            binding.btnNext.isEnabled = false
        }
    }

    /**
     * 获取默认账号
     */
    private fun getAmount(): String {
        var homeAmount = "300000"
        val customizeObj = CustomConfigHelper.getCmConfigData()
        if (customizeObj != null) {
            homeAmount = customizeObj.optString("homeAmount", "300000")
        }
        return homeAmount
    }

    /**
     * 获取手机号码内容
     */
    private fun getEditMobile(): String {
        return binding.editText.text.toString().trim()
    }

    /**
     * 获取是否是审核账号信息
     */
    private fun checkUncleConfigAccount(): JSONObject?{
        //发送验证码之前，需要验证手机号是否在 app配置 accList里存在
        val customize = CustomConfigHelper.getCmConfigData()
        var accItem: JSONObject? = null
        if (customize != null){
            val accList = customize.optJSONArray("accList")
            if (accList != null && accList.length() > 0){
                for (i in 0..<accList.length()){
                    val obj = accList.optJSONObject(i)
                    if (getEditMobile() == obj.optString("accM")){
                        accItem = obj
                        break
                    }
                }
            }
        }
        return accItem
    }

    /**
     * 获取本机手机号码
     */
    private fun loadCreditMolaSelfMobile(){
        val request: GetPhoneNumberHintIntentRequest = GetPhoneNumberHintIntentRequest.builder().build()
        Identity.getSignInClient(this)
            .getPhoneNumberHintIntent(request)
            .addOnSuccessListener { result: PendingIntent ->
                try {
                    phoneNumberHintIntentResultLauncher.launch(IntentSenderRequest.Builder(result).build())
                } catch (e: Exception) {
                    HHLog.e("Launching the PendingIntent failed")
                    showSikadwaEditTextMobile()
                }
            }
            .addOnFailureListener {
                HHLog.e("Phone Number Hint failed : OnFailureListener")
                showSikadwaEditTextMobile()
            }
    }

    private val phoneNumberHintIntentResultLauncher = registerForActivityResult(
        ActivityResultContracts.StartIntentSenderForResult()) { result ->
        try {
            var phoneNumber = Identity.getSignInClient(this).getPhoneNumberFromIntent(result.data)
            HHLog.e(">>>>>>>>>>>>>>>>>>>>>>>Phone Number $phoneNumber")
            addEvent(EventType.FORM.FORM_USER_LOGIN_SELF_MOBILE,phoneNumber)
            //时区区号
            val zoneCode = "+${Configs.getSPString(Configs.SPKEY.SIKADWA_TIMEZONE_CODE)}"
            phoneNumber = phoneNumber.replace(zoneCode,"")
            binding.editText.setText(phoneNumber)
            binding.editText.visibility = View.VISIBLE
            binding.textMaskMobile.visibility = View.GONE
            binding.editText.requestFocus()
            binding.editText.setSelection(getEditMobile().length)
        } catch(e: Exception) {
            HHLog.e("Phone Number Hint failed：${e.message}")
            addEvent(EventType.CLICK.CLICK_USER_LOGIN_SELF_MOBILE_CANCEL,e.message)
            showSikadwaEditTextMobile()
        }
    }

    /**
     * 显示手机号码输入框
     */
    private fun showSikadwaEditTextMobile(){
        binding.editText.visibility = View.VISIBLE
        binding.textMaskMobile.visibility = View.GONE

        lifecycleScope.launch {
            delay(200)
            binding.editText.requestFocus()
            onShowSoftInput(binding.editText)
            binding.editText.setSelection(getEditMobile().length) // 将光标设置到文本末尾
        }
    }

    /**
     * 登录成功
     */
    private fun onLoginSuccess(uid: String, token: String){
        //保存手机号码，个人中心使用
        Configs.saveSPString(Configs.SPKEY.SIKADWA_MOBILE, getEditMobile())
        //保存用户登录状态为已登录
        Configs.saveSPBoolean(Configs.SPKEY.SIKADWA_LOGIN,true)
        //保存用户id
        Configs.saveSPString(Configs.SPKEY.SIKADWA_USERID,uid)
        //保存用户Token
        Configs.saveSPString(Configs.SPKEY.SIKADWA_TOKEN,token)
        //初始化analysis lib 赋值 用户id 和 token
        TestAnalysisInit.initAnalysisLibAtLoginSuccess()

        hideLoading()
        onLoginSuccess()
    }

    /**
     * 登录成功
     */
    private fun onLoginSuccess() {
        onIntent(CreditActivity::class.java)
        finish()
    }

    /**
     * 登录
     */
    private fun loginAction(code: String,directLoginFlag: String){
        //登录之前，需要验证手机号是否在 app配置 accList里存在
        val accItem = checkUncleConfigAccount()
        //accList 存在该手机号，直接进入登录成功流程
        if (accItem != null){
            Configs.saveSPBoolean(Configs.SPKEY.SIKADWA_IS_CONFIG_ACCOUNT,true)
            onLoginSuccess(accItem.optString("accUid"),accItem.optString("accTk"))
            return
        }
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        val params = JSONObject().addCommonParams().apply {
            put("path",AppUrls.PATH.LOGIN_NO_CODE)
            put("mobile",getEditMobile())//手机号
            put("code",code)//验证码
            put("channelCode", GoogleInstallUtil.getInstallReferrer())//渠道号
            put("subChannelCode", GoogleInstallUtil.getInstallReferrer())//子渠道号
            put("directLoginFlag",directLoginFlag)//是否直接登录
            put("notBindWalletFlag","YES")//不自动绑卡
            put("loginParam","")//验证码接口返回的参数
        }
        postAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null){
                    val userId = obj.optString("userId","")
                    val userToken = obj.optString("token","")
                    val type = obj.optString("type")

                    //是否是渠道用户
                    val isAdSource = obj.optString("isAdSource")
                    if ("YES" == isAdSource){
                        Configs.saveSPBoolean(Configs.SPKEY.SIKADWA_IS_ADSOURCE,true)
                    }
                    onLoginSuccess(userId,userToken)
                }
            }

            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }

    override fun onStart() {
        super.onStart()
        addEvent(EventType.PAGE.PAGE_LOGIN_START, "")
    }

    override fun onDestroy() {
        super.onDestroy()
        addEvent(EventType.PAGE.PAGE_LOGIN_END, "")
    }
}